package org.zoomdev.zoom.dao.transaction;

import org.zoomdev.zoom.aop.Interceptor;
import org.zoomdev.zoom.aop.Invoker;
import org.zoomdev.zoom.common.utils.Classes;

import java.lang.reflect.Method;

public class TransMethodInterceptor implements Interceptor {


    private final int level;

    public TransMethodInterceptor(int level) {
        this.level = level;
    }


    @Override
    public Object intercept(Invoker invoker, Method method, Object target, Object[] args) throws Throwable {
        Transactions transactions = Transactions.get();
        try {
            transactions.beginTrans(level);
            Object ret = invoker.invoke(target, args);
            transactions.commitTrans();
            return ret;
        } catch (Throwable e) {
            transactions.rollbackTrans();
            throw Classes.getCause(e);
        }
    }
}
